import BackPage from '@/components/BackPage';
import Conversation from '@/components/Conversation';
import SaleBadge from '@/components/SaleBadge';
import SelectOne from '@/components/SelectOne';
import { finishReturn, getBySaleId, removeOrder, updState } from '@/services/orders';
import { getQueryParams } from '@/utils/utils';
import { EllipsisOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Dropdown, Menu, message, Popover, Space } from 'antd';
import moment from 'moment';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import SealModal from './components/ConfirmModal';
import CreateNew from './components/CreateNew';
import styles from './index.less';

const OrderManage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const qs = getQueryParams();
  const colorThem = localStorage.getItem('color') || '#1a7721';
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [ifDelete, setIfDelete] = useState('1');
  const [conversation, setConversation] = useState<boolean>(false);
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [selectList, setSelectList] = useState<any[]>([]);
  const [orderId, setOrderId] = useState<string>('');
  const [createNew, setCreateNew] = useState<boolean>(false);
  const [stateCurr, setStateCurr] = useState<string>('');
  const [userId, setUserId] = useState<string>('');

  // 分页的方法
  const handlePageChange = (page: any) => {
    setCurrentPage(page);
  };

  const getList = useCallback(async () => {
    try {
      const res = await getBySaleId({ pageIndex: currentPage, companyId: qs.id });
      setTotal(res.total);
      setList(res.list);
    } catch (error) {
      console.error(error);
    }
  }, [currentPage, qs.id]);

  useEffect(() => {
    getList();
  }, [getList]);

  const business = {
    businessid: '',
    address: '',
    companyname: '',
    key: '',
    name: '',
    price: 0,
    qty: 0,
    stock: 0,
    lastRoute: '',
  };
  // 操作确定弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };

  const actionFun = (record: any) => {
    setOrderId(record.id);
    setUserId(record.userId);
    setStateCurr(record.state);
  };

  const removedOrder = async () => {
    await removeOrder({ id: orderId }).then(() => {
      setIsModalVisible(false);
      getList();
      message.success('删除成功!');
    });
  };

  const returnOrder = async () => {
    await finishReturn({ id: orderId }).then(() => {
      setIsModalVisible(false);
      getList();
      message.success('退货签收成功!');
    });
  };

  const lotwoOrder = async () => {
    await updState({ id: orderId, state: '3' }).then(() => {
      setIsModalVisible(false);
      getList();
      message.success('配送成功!');
    });
  };

  const submitModalKey = (key: string) => {
    showModal();
    setIfDelete(key);
  };

  // 操作弹出的导航菜单
  const menu = (
    <Menu>
      <Menu.Item
        key={1}
        disabled={stateCurr !== '1'}
        onClick={() => {
          submitModalKey('1');
        }}
      >
        发货
      </Menu.Item>
      <Menu.Item
        key={2}
        disabled={stateCurr !== '2'}
        onClick={() => {
          submitModalKey('2');
        }}
      >
        配送
      </Menu.Item>
      {/* <Menu.Item
        key={3}
        disabled={stateCurr !== '5'}
        onClick={() => {
          submitModalKey('3');
        }}
      >
        <Tooltip placement="right" title={'订单结束后才可删除'}>
          删除
        </Tooltip>
      </Menu.Item> */}
      <Menu.Item
        key={5}
        disabled={stateCurr !== '9'}
        onClick={() => {
          submitModalKey('5');
        }}
      >
        退货签收
      </Menu.Item>
      <Menu.Item
        key={4}
        onClick={() => {
          setConversation(true);
        }}
      >
        联系买家
      </Menu.Item>
    </Menu>
  );

  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '订单编号',
      dataIndex: 'id',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '商品名称',
      dataIndex: 'goodsname',
      ellipsis: true,
    },
    {
      title: '买家昵称',
      dataIndex: 'username',
      copyable: true,
      ellipsis: true,
      render: (_, record) => (
        <Popover
          content={
            <div>
              <span>买家昵称：{record.username}</span>
              <div>购买地址：{record.useraddress}</div>
            </div>
          }
          title="买家信息"
        >
          <span>{record.username}</span>
        </Popover>
      ),
    },
    {
      title: '金额',
      dataIndex: 'amount',
      copyable: true,
      ellipsis: true,
      render: (_, record) => (
        <Popover
          content={
            <div>
              <div>订单完成后，平台会将金额的80%分配到您的账户</div>
            </div>
          }
          title={null}
        >
          <span>{(record.price * record.qty).toFixed(2)}</span>
        </Popover>
      ),
    },
    {
      title: '创建时间',
      key: 'timeadd',
      render: (text, record) => [
        <div key={record.id}>{`${moment(Number(record.timeadd)).format(
          'YYYY-MM-DD HH:mm:ss',
        )}`}</div>,
      ],
    },
    {
      title: '状态',
      dataIndex: 'saleState',
      filters: true,
      onFilter: true,
      ellipsis: true,
      valueType: 'select',
      valueEnum: {
        all: { text: '超长'.repeat(50) },
        '0': {
          text: '未发货',
          status: 'Error',
        },
        '6': {
          text: '未配送',
          status: 'Error',
        },
        '1': {
          text: '进行中',
          status: 'Success',
        },
        '2': {
          text: '已完成',
          status: 'Success',
        },
        '3': {
          text: '退货未签收',
          status: 'Error',
          disabled: true,
        },
        '4': {
          text: '已退货',
          status: 'Success',
          disabled: true,
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      render: (text, record) => [
        <div key={record.id} className={styles.drop}>
          <Dropdown
            overlay={menu}
            overlayClassName={styles.dropDownStyle}
            trigger={['click']}
            onVisibleChange={() => actionFun(record)}
          >
            <Space>
              <EllipsisOutlined style={{ fontSize: 28, color: '#999', cursor: 'pointer' }} />
            </Space>
          </Dropdown>
        </div>,
      ],
    },
  ];
  return (
    <BackPage thisRoute={'/ordermanage'} lastRoute={'订单管理'}>
      <div className={styles.container}>
        <SelectOne
          searchText={'订单编号'}
          fromWhere={'order'}
          selected={(value) => {
            setSelectList(value);
          }}
          clear={() => {
            setSelectList([]);
          }}
        />
        <ProTable<any>
          columns={columns}
          actionRef={actionRef}
          cardBordered={false}
          dataSource={selectList.length !== 0 ? selectList : list}
          editable={{
            type: 'multiple',
          }}
          rowKey="id"
          search={false}
          options={false}
          form={{
            // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
            syncToUrl: (values, type) => {
              if (type === 'get') {
                return {
                  ...values,
                  created_at: [values.startTime, values.endTime],
                };
              }
              return values;
            },
          }}
          pagination={{
            total,
            current: currentPage, // 当前页数
            pageSize: 10, // 每页条数
            size: 'small', // 分页的样式
            hideOnSinglePage: true, // 只有一页时是否隐藏分页器
            onChange: handlePageChange, // 分页的方法
          }}
          dateFormatter="string"
          headerTitle=""
        />
        {isModalVisible && (
          <SealModal
            ifDelete={ifDelete}
            handleCancel={() => {
              setIsModalVisible(false);
            }}
            delivery={() => {
              setIsModalVisible(false);
              ifDelete === '1' && setCreateNew(true);
            }}
            handleSeal={() => {
              ifDelete === '1'
                ? ''
                : ifDelete === '3'
                ? removedOrder()
                : ifDelete === '5'
                ? returnOrder()
                : lotwoOrder();
            }}
          />
        )}
        {createNew && (
          <CreateNew
            visible={createNew}
            getList={getList}
            handleCancel={() => {
              setCreateNew(false);
            }}
            orderId={orderId}
            handleNew={function (): void {
              throw new Error('Function not implemented.');
            }}
          />
        )}
        <Conversation
          color={colorThem}
          business={business}
          visible={conversation}
          onCancel={() => {
            setConversation(false);
          }}
          receiveId={userId}
        />
        <SaleBadge />
      </div>
    </BackPage>
  );
};
export default OrderManage;
